// WebSocket连接状态检查工具
import wsManager from './websocket.js';

export const websocketStatus = {
  // 检查WebSocket连接状态
  checkConnection: () => {
    const status = wsManager.getConnectionStatus();
    console.log('=== WebSocket连接状态 ===');
    console.log('连接状态:', status.isConnected ? '已连接' : '未连接');
    console.log('重连次数:', status.reconnectAttempts);
    console.log('连接URL:', status.url);
    console.log('=======================');
    
    return status;
  },
  
  // 测试WebSocket连接
  testConnection: () => {
    console.log('开始测试WebSocket连接...');
    
    // 检查浏览器支持
    if (typeof WebSocket === 'undefined') {
      console.error('❌ 浏览器不支持WebSocket');
      return false;
    }
    
    // 检查当前连接状态
    const status = wsManager.getConnectionStatus();
    if (status.isConnected) {
      console.log('✅ WebSocket已连接');
      return true;
    }
    
    console.log('⚠️ WebSocket未连接，尝试重新连接...');
    wsManager.connect();
    
    // 等待连接结果
    return new Promise((resolve) => {
      const timeout = setTimeout(() => {
        console.log('❌ WebSocket连接超时');
        resolve(false);
      }, 5000);
      
      const checkConnection = () => {
        const currentStatus = wsManager.getConnectionStatus();
        if (currentStatus.isConnected) {
          clearTimeout(timeout);
          console.log('✅ WebSocket连接成功');
          resolve(true);
        } else if (currentStatus.reconnectAttempts >= 5) {
          clearTimeout(timeout);
          console.log('❌ WebSocket连接失败，已达到最大重连次数');
          resolve(false);
        } else {
          setTimeout(checkConnection, 1000);
        }
      };
      
      checkConnection();
    });
  },
  
  // 获取连接建议
  getConnectionAdvice: (errorCode) => {
    const advice = {
      1006: [
        '检查后端服务是否正在运行',
        '确认WebSocket服务已启动',
        '检查网络连接是否正常',
        '确认防火墙没有阻止连接',
        '检查端口8088是否被占用'
      ],
      1001: [
        '连接被正常关闭',
        '检查是否有代码主动断开了连接'
      ],
      1002: [
        '协议错误',
        '检查WebSocket协议版本是否匹配'
      ],
      1003: [
        '不支持的数据类型',
        '检查发送的数据格式是否正确'
      ]
    };
    
    return advice[errorCode] || ['请检查网络连接和后端服务状态'];
  }
};

export default websocketStatus;
